package com.aikg.kgrag_java.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName: UrlUtils
 * @Description: 调用web接口的工具类
 * @Author: 李宗雨
 * @Date: 2024/12/26 18:19
 * @Version: 1.0
 **/
public class UrlUtils {

    public static SseEmitter httpRequestBySSE(String urlStr, Object bodyParam){
        SseEmitter emitter = new SseEmitter();

        // 启动一个新线程来处理流式数据
        new Thread(() -> {
            try {
                URL url = new URL(urlStr);  // 目标流式数据接口
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                // 设置请求头，表明发送的是JSON数据
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                // 允许写入数据到请求体
                connection.setDoOutput(true);
                // 使用ObjectMapper将对象转换为JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonRequest = objectMapper.writeValueAsString(bodyParam);
                try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                    wr.writeBytes(jsonRequest);
                    wr.flush();
                }
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        emitter.send(line.substring(5), MediaType.APPLICATION_JSON);  // 将每行数据发送给前端
                    }
                }

                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;

    }

    public static String httpRequest(String urlStr, Object bodyParam){
        try {
            // API的URL地址
            URL url = new URL(urlStr);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST（因为通过body传参，通常是POST请求，根据实际接口要求调整）
            con.setRequestMethod("POST");
            // 设置请求头，表明发送的是JSON数据
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            // 允许写入数据到请求体
            con.setDoOutput(true);

            // 使用ObjectMapper将对象转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonRequest = objectMapper.writeValueAsString(bodyParam);
            try (OutputStream os = con.getOutputStream()){
                byte[] input = jsonRequest.getBytes(StandardCharsets.UTF_8);
                os.write(input,0, input.length);
            }
            // 获取响应码
            int responseCode = con.getResponseCode();
            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {  // 假设200表示成功，根据实际调整
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine())!= null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println("Response Body: " + response.toString());
                return response.toString();
            } else {
                System.out.println("请求失败，响应码: " + responseCode);
            }
            // 关闭连接
            con.disconnect();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }

}
